const querystring = require('querystring');
const {resolve} = require('path');
const fs = require('fs');
 // 返回模板
 exports.ReturnData = (code=200,msg='参数不能空',data,total) => {
    return  {
        code,
        msg,data,total
    }
}

 // 生成token
 exports.create_token = function(leng) {
     leng = leng == undefined ? 32 : leng; //如果没设置token长度自动为32位
     let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz23456789';
     let token = '';
     for (let i = 0; i < leng; ++i) {
         token += chars.charAt(Math.floor(Math.random() * chars.length))
     }
     return token ///返回之前使用md5加密一下
 };

 // 生成按日期名字
const create_timeName = function (){
    let obj = new Date();
    let D = {};
    D['year'] = obj.getFullYear();
    D['month'] = (obj.getMonth() + 1) >= 10 ? (obj.getMonth() + 1) : "0" + (obj.getMonth() + 1);
    D['date'] = obj.getDate() >= 10 ? obj.getDate() : "0" + obj.getDate();
    D['hour'] = obj.getHours() >= 10 ? obj.getHours() : "0" + obj.getHours();
    D['minute'] = obj.getMinutes() >= 10 ? obj.getMinutes() : "0" + obj.getMinutes();
    D['second'] = obj.getSeconds() >= 10 ? obj.getSeconds() : "0" + obj.getSeconds();
    return '' + D.year + D.month + D.date + D.hour + D.minute + D.second
}
 exports.create_timeName = create_timeName

 // 将上传的图片存到本地
 exports.SaveImgToLocal = async function(req,respone,callback) {
     let uuid = () => {  //生成uuid方法
         let s = [];
         let hexDigits = "0123456789abcdef";
         for (let i = 0; i < 36; i++) {
             s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
         }
         s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
         s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
         s[8] = s[13] = s[18] = s[23] = "-";
         let uuid = s.join("");
         return uuid;
     }
     req.setEncoding('binary');
     let body = '';   // 文件数据
     // 边界字符串
     let boundary = req.headers['content-type'].split('; ')[1].replace('boundary=', '');
     //接收post如data 流 buffer
     req.on('data', async function (d) {
         body += d;
     });


     await req.on('end', function () {
         let file = querystring.parse(body, '\r\n', ':');
         console.log(file['Content-Disposition']);
         let fileInfo = file['Content-Disposition'].split('; ');
         let fileName = '';
         let ext = '';
         for (let value in fileInfo) {
             if (fileInfo[value].indexOf("filename=") != -1) {
                 fileName = fileInfo[value].substring(10, fileInfo[value].length - 1);

                 if (fileName.indexOf('\\') != -1) {
                     fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);
                 }
                 ext = fileName.substr(fileName.indexOf('.') + 1, fileName.length);
             }
         }

         let upperBoundary = body.toString().indexOf(file['Content-Type'].substring(1)) + file['Content-Type'].substring(1).length;

         let binaryDataAlmost = body.toString().substring(upperBoundary).replace(/^\s\s*/, '').replace(/\s\s*$/, '');

         // 上传文件重命名
         let uuidFileName = `${uuid()}.${ext}`
         //上传文件 本地存放地址
         let uploadDirFile = `../public/UploadFileList/${uuidFileName}`

         //创建文件流
         let writerStream = fs.createWriteStream(uploadDirFile);

         //开始 —— 写入文件到本地
         writerStream.write(binaryDataAlmost.substring(0, binaryDataAlmost.indexOf(`--${boundary}--`)), 'binary');
         //写入完成
         writerStream.end();
         writerStream.on('finish', function () {
             //删除刚刚创建好的本地文件 -> 只有在把文件存起来的时候需要删除掉本地，否则不要用。
             // fs.unlinkSync(uploadDirFile)
             callback({
                 code:200,
                 msg:'上传成功~',
                 data:`/UploadFileList/${uuidFileName}`
             })
         });
     });
 }

